﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Threading;
using Core.Helper;
using DataServer.Annotations;
using log4net;

namespace DataServer.View
{
    /// <summary>
    /// UrlTester.xaml 的交互逻辑
    /// </summary>
    public partial class UrlTester
    {
        private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public ObservableCollection<UrlFormat> UrlFormats = new ObservableCollection<UrlFormat>();
        private readonly DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Normal);
        object _locker =new object();
        public UrlTester()
        {
            InitializeComponent();
            timer.Interval = TimeSpan.FromSeconds(10);
            timer.Tick += Timer_Tick;
            timer.Start();
          
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            lock (_locker)
            {
                try
                {
                    string html = NetHelper.HttpGet("http://localhost/control/help");
                    List<string> result = getUrls(html);
                    if (result != null && result.Count > 0)
                    {
                        timer.Stop();
                        timer.Tick -= Timer_Tick;
                        int index = 0;
                        foreach (string s in result)
                        {
                          
                            if (s.Contains("/his/") || s.Contains("ModifyData") || s.Contains("realtimedata") ||
                                s.Contains("command"))
                            {
                                index++;
                                UrlFormats.Add(new UrlFormat(index, s));
                            }
                        }
                        _log.Info("Url加载成功,现在可进行测试!");
                        
                    }
                    
                }
                catch (Exception ex)
                {
                    _log.Error("Url加载异常:" + ex.Message);
                }
                cbbSourceUrl.ItemsSource = UrlFormats;
            }
        }

        private List<string> getUrls(string html)
        {
            List<string> list = new List<string>();
            Regex regex = new Regex("title=\"(.*?)\">");
            MatchCollection collection = regex.Matches(html);
            foreach (Match match in collection)
            {
                list.Add(match.Groups[1].Value.Replace("&amp;","&"));
            }
            return list;
        }

        private void CbbSourceUrl_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            gridTarget.DataContext = null;
            gridTarget.DataContext = cbbSourceUrl.SelectedItem;
            UrlFormat select = cbbSourceUrl.SelectedItem as UrlFormat;
            if (select != null)
            {
                listBoxParameter.DataContext = select.Parameters;
            }
            else
            {
                listBoxParameter.DataContext = null;
            }
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\r\n";
            UrlFormat urlFormat = cbbSourceUrl.SelectedItem as UrlFormat;
            RequetResult.Text = date;
            if (urlFormat != null)
            {
                try
                {
                    string result = NetHelper.HttpGet(urlFormat.TargetUrl);
                    RequetResult.Foreground = Brushes.DarkGreen;
                    RequetResult.Text = date+JsonHelper.JsonTree(result);
                }
                catch (Exception ex)
                {
                    RequetResult.Foreground = Brushes.Red;
                    RequetResult.Text = date+"异常:" + ex.Message;
                }
            }
            else
            {
                RequetResult.Foreground = Brushes.Orange;
                RequetResult.Text = date+ "请选择测试目标对象!";
            }
        }

        private void FrameworkElement_OnSourceUpdated(object sender, DataTransferEventArgs e)
        {
            UrlFormat urlFormat = cbbSourceUrl.SelectedItem as UrlFormat;
            TextBox txt = sender as TextBox;
            if (urlFormat != null&& txt != null && txt.DataContext is Parameter)
            {
                //Parameter parameter = txt.DataContext as Parameter;
                string temp = urlFormat.SourceUrl;
                foreach (Parameter formatParameter in urlFormat.Parameters)
                {
                    temp = temp.Replace("{" + formatParameter.Name + "}", formatParameter.Value);
                }
                urlFormat.TargetUrl = temp;
            }
        }
    }

    public class UrlFormat: INotifyPropertyChanged
    {
        public int Id { get; set; }
        private string _sourceUrl;
        private string _targetUrl;
        public ObservableCollection<Parameter> Parameters { get; set; }

        public string SourceUrl
        {
            get => _sourceUrl;
            set
            {
                _sourceUrl = value;
                OnPropertyChanged("SourceUrl");
            } 
        }
        public string TargetUrl
        {
            get => _targetUrl;
            set
            {
                _targetUrl = value;
                OnPropertyChanged("TargetUrl");
            }
        }

        public UrlFormat(int id,string url)
        {
            Parameters = new ObservableCollection<Parameter>();
            Id = id;
            SourceUrl = url;
            TargetUrl = url;
            Regex regex = new Regex("{(.*?)}");
            MatchCollection collection = regex.Matches(url);
            foreach (Match match in collection)
            {
                Parameter parameter = new Parameter();
                parameter.Name = match.Value.Replace("{","").Replace("}","");
                Parameters.Add(parameter);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class Parameter:INotifyPropertyChanged
    {
        private string _name;
        private string _value;

        public string Name
        {
            get => _name;
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
        public string Value
        {
            get => _value;
            set
            {
                _value = value;
                OnPropertyChanged("Value");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

}
